package com.example.supermarket_back.utils.email;

import com.example.supermarket_back.config.cache.CacheConfig;
import com.example.supermarket_back.entity.ToEmail;
import com.example.supermarket_back.utils.VerCodeGenerateUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;

@Component
public class Email {
    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromAddress;

    @Resource
    TemplateEngine templateEngine;

    @Resource
    private CacheConfig cacheConfig;

    public boolean sendEmailVerificationCode(ToEmail toEmail) {
        boolean flag=false;
        // 创建邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            String code=VerCodeGenerateUtil.generateVerCode();
            //将验证码存入redis
            cacheConfig.addCaptchaToRedis(toEmail.getTos(),code);
            // 设置发件人
            helper.setFrom(new InternetAddress(fromAddress, "系统通知"));
            // 设置收件人
            helper.setTo(toEmail.getTos());
            // 设置主题
            helper.setSubject(toEmail.getSubject());
            // 使用Thymeleaf模板引擎渲染HTML模板
            Context context = new Context();
            context.setVariable("verCode", Arrays.asList(code.split("")));
            String content = templateEngine.process("recodeRegister", context);
            // 设置内容
            helper.setText(content, true);
            // 发送邮件
            javaMailSender.send(message);
            flag=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
